import Model.CellMsgModel;
import Util.ExcelUtil;
import word.WordTemplate;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/2/11.
 */
public class WordReplace {
    public static String Run(String excelfilepath, String tamplateSheetName , String targetSheetName , String wordFilePath) throws IOException {
        System.out.println(excelfilepath);
        System.out.println(tamplateSheetName);
        System.out.println(targetSheetName);
        System.out.println(wordFilePath);


        Map<String, CellMsgModel> parameterMap = new HashMap<>();
        String msg = "";
        //取模板sheet中的参数,
        try {
            parameterMap = ExcelUtil.getmyExcelKeyList(excelfilepath,tamplateSheetName);
        } catch (Exception e) {
            return "读取参数列表的时候出现错误："+e.getMessage();
        }

        try {
            parameterMap = ExcelUtil.getmyExcelMsg(excelfilepath,targetSheetName,parameterMap);
        } catch (IOException e) {
            return "读取参数数值的时候出现错误："+e.getMessage();
        }

        System.out.println("搜索到" + parameterMap.size() + "个参数");

        String fileType = wordFilePath.substring(wordFilePath.lastIndexOf(".") + 1, wordFilePath.length());
        String DOCX_FILE_WRITE = wordFilePath.substring(0, wordFilePath.length()-(fileType.length()+1))+"-replace." + fileType;

        System.out.println(DOCX_FILE_WRITE);

        Map<String,String> map = new HashMap<String, String>();

        for ( String s:
                parameterMap.keySet()) {
            //System.out.println(s +":" + parameterMap.get(s).getCol() + "," + parameterMap.get(s).getRow());
            map.put(s,parameterMap.get(s).getValue());
        }
        System.out.println("开始替换");
        File file = new File(wordFilePath);
        FileInputStream fileInputStream = null;
        WordTemplate template = null;
        File filewrite = new File(DOCX_FILE_WRITE);
        FileOutputStream out;
        try {
            fileInputStream = new FileInputStream(file);
            template = new WordTemplate(fileInputStream);
            template.replaceTag(map);
            out = new FileOutputStream(filewrite);
            BufferedOutputStream bos = new BufferedOutputStream(out);
            template.write(bos);
        } catch(IOException exception){
            return "创建word的时候："+exception.getMessage();
        }
        msg = "转换完成";
        return msg;


    }
}
